package com.zhongdaima.netty.analysis.part0.jdk.bio;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;

/**
 * 欢迎关注公众号“种代码“，获取博主微信深入交流
 *
 * @author wangjianxin
 */
public class BioServerHandler {
    private final Socket socket;

    public BioServerHandler(Socket socket) {
        this.socket = socket;
    }

    public void start() {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        InputStream inputStream = socket.getInputStream();
                        byte[] buffer = new byte[1024];
                        //阻塞操作，因为不知道inputStream中什么时候会有数据可读，只能阻塞在这里等待
                        //每一个连接都要消耗一个线程
                        int readLength = inputStream.read(buffer);
                        if (readLength != -1) {
                            String name = new String(buffer, 0, readLength);
                            System.out.println(name);
                            //打印客户端发送过来的数据
                            socket.getOutputStream().write(("hello, " + name).getBytes());
                        }
                    } catch (Throwable e) {
                        try {
                            socket.close();
                        } catch (IOException ioException) {
                        }
                    }
                }
            }
        });
        thread.start();
    }
}
